package cn.opencodes.framework.tools.utils;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
 * 对称加密辅助类
 * @author hj
 */
public class AESUtils {
	
	/**
     * 加密 AES-256
     * @param content 待加密内容
     * @param password 密钥
     */
	public static String encryptByAES(String content, String password) throws Exception {
		try {  
            Security.addProvider(new BouncyCastleProvider());  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");  
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));  
            byte[] byteContent = content.getBytes("utf-8");  
            byte[] cryptograph = cipher.doFinal(byteContent);  
            return Base64.getEncoder().encodeToString(cryptograph);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
	}
	
	
    /**
     * 解密 AES-256
     * @param decryptCode 待解密内容
     * @param password 密钥
     */
    public static String decryptByAES(String decryptCode, String password) throws Exception {
    	byte[] data = Base64.getDecoder().decode(decryptCode);
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
        return new String(cipher.doFinal(data), "UTF-8");
    }
    
    /**
     * 生成加密秘钥
     */
    private static SecretKeySpec getSecretKey(final String password) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance("AES");
            //AES 要求密钥长度为 128
            kg.init(128, new SecureRandom(password.getBytes()));
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), "AES");// 转换为AES专用密钥
        } catch (NoSuchAlgorithmException e) {
        	e.printStackTrace();
        }
        return null;
    }

}
